package com.frm.controller;

import com.plug.TimeUtils;
import com.plug.result.RetResponse;
import com.plug.result.RetResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 创建人:    xvzhe
 * 创建时间:
 * 修改时间:
 * 版本:      v1.0
 */
@RestController
public class ImgController {
    @Value("${folderPath}")
    private String folderPath;
    @Value("${folderType}")
    private String folderType;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;

    @RequestMapping("upload")
    public RetResult photoUpload(MultipartFile file) throws Exception {
        Map<String, Object> res = new LinkedHashMap<String, Object>();
        try {
            String pa = folderPath + File.separator + request.getParameter("project");
            File f = new File(pa);
            if (!f.exists()) {
                f.mkdirs();
            }
            String day = TimeUtils.getTimeFormat().substring(0, 10);
            String pathDay = pa + File.separator + day;
            if (!StringUtils.isEmpty(file) && file.getSize() > 0) {
                String filename = file.getOriginalFilename();
                String suffix = filename.substring(filename.lastIndexOf(".") + 1);
                if (!folderType.contains(suffix.toUpperCase())) {
                    return RetResponse.makeErrRsp("非法的文件！");
                }
                String names = TimeUtils.getTimeStmp() + "." + suffix;
                names = names.toLowerCase();
                String realPath = pathDay + File.separator + names;
                File newFile = new File(realPath);
                if (!newFile.exists()) {
                    newFile.mkdirs();
                }
                file.transferTo(newFile);
                return RetResponse.makeOKRsp("/" + request.getParameter("project") + "/" + day + "/" + names);
            } else {
                return RetResponse.makeErrRsp("文件不存在！");
            }
        } catch (Exception e) {
            return RetResponse.makeErrRsp("未知错误");
        }
    }

    @RequestMapping("uploadsWang")
    public RetResult uploadsWang(@RequestParam(value = "myFileName") MultipartFile mf) {
        String realPath = folderPath;
        try {
            if (!StringUtils.isEmpty(mf) && mf.getSize() > 0) {
                String filename = mf.getOriginalFilename();
                String[] names = filename.split("\\.");//
                String tempNum = (int) (Math.random() * 100000) + "";
                if (!folderType.contains(names[1].toUpperCase())) {
                    return RetResponse.makeErrRsp("非法的文件！");
                }
                String uploadFileName = tempNum + System.currentTimeMillis() + "." + names[names.length - 1];
                File targetFile = new File(realPath, uploadFileName);
                mf.transferTo(targetFile);
                return RetResponse.makeOKRsp(uploadFileName);
            }
        } catch (Exception e) {
            return RetResponse.makeErrRsp();
        }
        return RetResponse.makeErrRsp();
    }

    @RequestMapping("file/{time}")
    public void getFiles(@PathVariable("time") String time) {
        String path = "/" + time;
        File imageFile = new File(folderPath + path);
        if (imageFile.exists()) {
            FileInputStream fis = null;
            OutputStream os = null;
            try {
                fis = new FileInputStream(imageFile);
                os = response.getOutputStream();
                int count = 0;
                byte[] buffer = new byte[1024 * 8];
                while ((count = fis.read(buffer)) != -1) {
                    os.write(buffer, 0, count);
                    os.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    fis.close();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @RequestMapping("file/{projectId}/{date}/{time}")
    public void getFile(@PathVariable("projectId") String projectId, @PathVariable("date") String date, @PathVariable("time") String time) {
        String path = "/" + projectId + "/" + date + "/" + time;
        File imageFile = new File(folderPath + path);
        if (imageFile.exists()) {
            FileInputStream fis = null;
            OutputStream os = null;
            try {
                fis = new FileInputStream(imageFile);
                os = response.getOutputStream();
                int count = 0;
                byte[] buffer = new byte[1024 * 8];
                while ((count = fis.read(buffer)) != -1) {
                    os.write(buffer, 0, count);
                    os.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    fis.close();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
